package com.ruge.core.serializer;

import com.alibaba.fastjson2.filter.ValueFilter;
import com.ruge.core.annotation.PrivacyEncrypt;
import com.ruge.core.enums.PrivacyTypeEnum;
import com.ruge.core.tool.PrivacyTool;
import com.ruge.tool.str.StringTool;
import lombok.AllArgsConstructor;
import lombok.NoArgsConstructor;
import lombok.extern.slf4j.Slf4j;

import java.lang.reflect.Field;

/**
 * description:
 * create time at 2022/6/9 16:51
 *
 * @author alice.ruge
 * @since 0.0.3
 */
@Slf4j
@NoArgsConstructor
@AllArgsConstructor
public class PrivacySerializerValueFilter implements ValueFilter {

    /**
     * 脱敏类型
     */
    private PrivacyTypeEnum privacyTypeEnum;
    /**
     * 前几位不脱敏
     */
    private Integer prefixNoMaskLen;
    /**
     * 最后几位不脱敏
     */
    private Integer suffixNoMaskLen;
    /**
     * 用什么打码
     */
    private String symbol;

    @Override
    public Object apply(Object object, String name, Object value) {
        try {
            Field field = object.getClass().getDeclaredField(name);
            PrivacyEncrypt privacyEncrypt = field.getAnnotation(PrivacyEncrypt.class);
            if (StringTool.isBlank(privacyEncrypt)) {
                return value;
            }
            String valueStr = (String) value;
            PrivacyTypeEnum type = privacyEncrypt.type();
            switch (type) {
                case CUSTOMER:
                    return PrivacyTool.desValue(valueStr, prefixNoMaskLen, suffixNoMaskLen, symbol);
                case NAME:
                    return PrivacyTool.hideChineseName(valueStr);
                case ID_CARD:
                    return PrivacyTool.hideIDCard(valueStr);
                case PHONE:
                    return PrivacyTool.hidePhone(valueStr);
                case EMAIL:
                    return PrivacyTool.hideEmail(valueStr);
                default:
                    throw new IllegalArgumentException("unknown privacy type enum " + privacyTypeEnum);
            }
        } catch (NoSuchFieldException e) {
            log.error("当前数据类型为{},值为{}", object.getClass(), value);
            return value;
        }
    }
}
